package web;

import service.Login;
import service.PersonService;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String identity=req.getParameter("identity");
        String name=req.getParameter("user");
        String pwd=req.getParameter("pwd");
        System.out.println(identity+"登录");
        HttpSession session=req.getSession();
        session.setAttribute("username",name);
        session.setAttribute("identity",identity);
        boolean result=false;
        if(identity.equals("student")){
            result= Login.validateStudent(name,pwd);
            if(result){
                System.out.println(identity+"登录成功");
                Cookie cookieName=new Cookie("username",name);
                cookieName.setMaxAge(60*60*24);  //设置cookie的生存时间为1天
                cookieName.setPath("/College_war_exploded");
                resp.addCookie(cookieName);
                Cookie cookiePwd=new Cookie("password",pwd);
                cookiePwd.setMaxAge(60*60*24);
                cookiePwd.setPath("/College_war_exploded");
                resp.addCookie(cookiePwd);
                Cookie cookieIdentity=new Cookie("identity",identity);
                cookieIdentity.setMaxAge(60*60*24);  //设置cookie的生存时间为1天
                cookieIdentity.setPath("/College_war_exploded");
                resp.addCookie(cookieIdentity);
                resp.getWriter().write("true");
            }else {
                resp.getWriter().write("false");
            }
        }else if(identity.equals("teacher")){
            result= Login.validateTeacher(name,pwd);
            if(result){
//                resp.sendRedirect("Teacher.html");
                System.out.println(identity+"登录成功");
                Cookie cookieName=new Cookie("username",name);
                cookieName.setMaxAge(60*60*24);  //设置cookie的生存时间为1天
                cookieName.setPath("/College_war_exploded");
                resp.addCookie(cookieName);
                Cookie cookiePwd=new Cookie("password",pwd);
                cookiePwd.setMaxAge(60*60*24);
                cookiePwd.setPath("/College_war_exploded");
                resp.addCookie(cookiePwd);
                Cookie cookieIdentity=new Cookie("identity",identity);
                cookieIdentity.setMaxAge(60*60*24);  //设置cookie的生存时间为1天
                cookieIdentity.setPath("/College_war_exploded");
                resp.addCookie(cookieIdentity);
                resp.getWriter().write("true");
            }else {
                resp.getWriter().write("false");
            }
        }
    }
}
